<template>
  <div class="addaddr">
    <van-nav-bar
      :title="this.$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-address-edit
      :area-list="areaList"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @change-detail="onChangeDetail"
    />
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import {
  addAddressApi,
  getAddresslistApi,
  updateAddressApi,
} from "@/api/address.js";
export default {
  data() {
    return {
      areaList,
      searchResult: [],
    };
  },
  methods: {
    // 保存地址
    async onSave(AddressInfo) {
      console.log(AddressInfo);
      const addrlist = await getAddresslistApi();
      // 判断添加的地址是否为默认地址
      if (AddressInfo.isDefault == true) {
        let defaultaddr = [];
        // 遍历原来的地址列表，获取原来的默认地址
        defaultaddr = addrlist.addresses.filter(
          (addr) => addr.isDefault == true
        );
        // 如果原来有默认地址
        if (defaultaddr.length != 0) {
          // 将原来的默认地址更新为false
          defaultaddr[0].isDefault = false;
          updateAddressApi(defaultaddr[0]._id, defaultaddr[0]);
        }
      }
      // 添加新的地址到地址列表
      const result = await addAddressApi(AddressInfo);
      console.log(result);
      this.$router.push("/addresslist");
    },
    // 点击返回按钮
    async onClickLeft() {
      this.$router.push("/addresslist");
    },
    onChangeDetail(val) {
      if (val) {
        this.searchResult = [];
      } else {
        this.searchResult = [];
      }
    },
  },
};
</script>

<style>

.addaddr {
  padding-top: 50px;
}

.addaddr .van-button--danger {
  background-color: #000;
  border-color: #000;
}
.addaddr .van-switch--on {
  background-color: #0058a3;
}
.addaddr textarea {
  height: 45px !important;
}
.addaddr .van-cell {
  line-height: 45px;
}
.addaddr .van-nav-bar .van-icon,
.addaddr .van-nav-bar__text {
  color: #000;
}
.addaddr .van-nav-bar {
  position: fixed;
  width: 100%;
  top: 0;
}
</style>
